package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;
    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1. 检查参数
        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 上传图片到minio中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName+postfix, multipartFile.getInputStream());
            log.info("上传图片到minio中, fileId: {}", fileId);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl-上传文件失败");
            throw new RuntimeException(e);
        }
        // 3. 保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        // 4. 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1. 检查参数
        dto.checkParam();
        // 2. 分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        // 是否收藏
        if(dto.getIsCollection() != null && dto.getIsCollection() == 1){
            queryWrapper.eq(WmMaterial::getIsCollection, 1);
        }
        // 按照用户查询
        queryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        // 按照时间倒序排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        page(page, queryWrapper);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        // 3. 结果返回
        return result;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 图片删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1. 参数检验
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 查询图片
        WmMaterial material = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id));
        if(material == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 查询图片是否被引用
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper1);
        if(count > 0){
            return ResponseResult.errorResult(501, "文件使用中, 删除失败");
        }
        // 4. 查询图片是否被收藏
        WmMaterial wmMaterial = getById(id);
        Short isCollection = wmMaterial.getIsCollection();
        if(isCollection == 1){
            return ResponseResult.errorResult(501, "文件收藏中, 删除失败");
        }
        // 5. 删除图片
        // 5.1 删除minio中的图片
        String materialUrl = material.getUrl();
        fileStorageService.delete(materialUrl);
        // 5.2 删除数据库中的图片
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 图片收藏函数
     * @param id
     * @param isCollection
     * @return
     */
    public ResponseResult collectFunc(Integer id, Short isCollection)
    {
        // 1. 参数检验
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 更新isCollection属性
        WmMaterial wmMaterial = getById(id);
        wmMaterial.setIsCollection((short) isCollection);
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 图片取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        return collectFunc(id, WemediaConstants.CANCEL_COLLECT_MATERIAL);
    }

    /**
     * 图片收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        return collectFunc(id, WemediaConstants.COLLECT_MATERIAL);
    }
}
